package hsintiao.com.xintiaoAPP.service.impl;

import hsintiao.com.xintiaoAPP.entity.BodyInformation;
import hsintiao.com.xintiaoAPP.entity.User;
import hsintiao.com.xintiaoAPP.entity.vo.UserBodyVO;
import hsintiao.com.xintiaoAPP.entity.vo.UserYVO;
import hsintiao.com.xintiaoAPP.mapper.BodyInformationMapper;
import hsintiao.com.xintiaoAPP.mapper.UserMapper;
import hsintiao.com.xintiaoAPP.service.UserService;
import hsintiao.com.xintiaoAPP.util.AjaxResult;
import hsintiao.com.xintiaoAPP.util.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BodyInformationMapper bodyInformationMapper;
    @Override
    public User getUserByID(Long id) {
        return userMapper.getUserByID(id);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    /*
    * 保存身体信息
    * */
    @Override
    public AjaxResult saveBodyInformation(UserBodyVO vo) {
        try {

            User user = new User();
            Long userID = vo.getId();
            user.setId(userID);
            user.setName(vo.getName());
            //获取性别判断属于哪一个
            String gender = vo.getGender();
            if(StringUtils.isNotBlank(gender) && gender.trim().length()>0){
                if("男".equals(gender)){
                    user.setGender("男");
                }else {
                    user.setGender("女");
                }
            }
            //获取身体转换为Date
            String birthday = vo.getBirthday();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            //如果生日为空则设置当前时间为生日
            if(StringUtils.isBlank(birthday) || birthday.trim().length()==0 || "".equals(birthday)){
                date = new Date();
            }else {
                date = format.parse(birthday);
            }
            user.setBirthday(date);
            //user.setAvatar("http://121.196.124.143:8888/"+vo.getAvatar());
            //设置头像地址
            user.setAvatar(vo.getAvatar());
            //更新user的其他基本信息
            userMapper.updateUser(user);

            StringBuilder heartMedicalHistory = new StringBuilder();
            //设置病史信息(拼接成字符串)
            if(vo.getDxxdgh() !=null && !vo.getDxxdgh().equals("")){//窦性心动过缓
                heartMedicalHistory.append(vo.getDxxdgh()).append(",");
            }
            if(vo.getDxzb() !=null && !vo.getDxzb().equals("")){//窦性早搏
                heartMedicalHistory.append(vo.getDxzb()).append(",");
            }
            if(vo.getDxxdgs() !=null && !vo.getDxxdgs().equals("")){//窦性心动过速
                heartMedicalHistory.append(vo.getDxxdgs()).append(",");
            }
            if(vo.getDxxvbq() !=null && !vo.getDxxvbq().equals("")){//窦性心律不齐
                heartMedicalHistory.append(vo.getDxxvbq()).append(",");
            }
            if(vo.getDxtb() !=null && !vo.getDxtb().equals("")){//窦性停搏
                heartMedicalHistory.append(vo.getDxtb()).append(",");
            }
            if(vo.getFscdzz() !=null && !vo.getFscdzz().equals("")){//房事传导阻滞
                heartMedicalHistory.append(vo.getFscdzz()).append(",");
            }
            if(vo.getSsxzb() !=null && !vo.getSsxzb().equals("")){//室上性早搏
                heartMedicalHistory.append(vo.getSsxzb()).append(",");
            }
            if(vo.getZfxssxxdgs() !=null && !vo.getZfxssxxdgs().equals("")){//阵发性室上性心动过速
                heartMedicalHistory.append(vo.getZfxssxxdgs()).append(",");
            }
            if(vo.getZfxsxxdgs() !=null && !vo.getZfxsxxdgs().equals("")){//阵发性室性心动过速
                heartMedicalHistory.append(vo.getZfxsxxdgs()).append(",");
            }
            if(vo.getXfpd() !=null && !vo.getXfpd().equals("")){//心房扑动
                heartMedicalHistory.append(vo.getXfpd()).append(",");
            }
            if(vo.getXfxc() !=null && !vo.getXfxc().equals("")){//心房纤颤
                heartMedicalHistory.append(vo.getXfxc()).append(",");
            }
            if(vo.getXspd() !=null && !vo.getXspd().equals("")){//心室扑动
                heartMedicalHistory.append(vo.getXspd()).append(",");
            }
            //stringbuilder判断是否为空追加到字符串中
            BodyInformation body = new BodyInformation();
            //去除最后一个，字符
            if(heartMedicalHistory.length() == 0 || heartMedicalHistory == null){
                heartMedicalHistory.append("    ");
            }
            String s = heartMedicalHistory.toString();
            String substring = s.substring(0, s.length() - 1);
            //设置心脏病、高血压、糖尿病、其他病史
            body.setHeartMedicalHistory(substring);
            body.setHypertensionMedicalHistory(vo.getGxy());
            body.setDiabetesMedicalHistory(vo.getTlb());
            body.setOtherMedicalHistory(vo.getOtherMedicalHistory());
            body.setWeight(vo.getWeight());
            body.setHeight(vo.getHeight());
            body.setUserID(userID);
            BodyInformation byUserId = bodyInformationMapper.findByUserId(userID);
            if(byUserId != null && byUserId.getId() != null){
                body.setId(byUserId.getId());
                bodyInformationMapper.update(body);
            }else {
                bodyInformationMapper.insert(body);
            }
            return AjaxResult.me().setMessage("保存成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setCode(ResponseCode.FAILURE.getCode())
                    .setSuccess(false).setMessage("保存失败");
        }

    }

    /*
    * 获取最新的用户信息
    * */
    @Override
    public AjaxResult getUserByUpdate(Long id) {
        try {
            User user = userMapper.getUserByID(id);
            return AjaxResult.me().setResultObj(user);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setCode(ResponseCode.FAILURE.getCode())
                    .setSuccess(false).setMessage("查询更新数据失败");
        }
    }

    /*
    * 检查诊断资格
    * */
    @Override
    public AjaxResult checkDiagnostic(Long userID) {
        try {
            User userByID = userMapper.getUserByID(userID);
            Date date = userByID.getDiagnosticValidityperiod();
            if(date == null && date.getTime() == 0){
                date.setTime(0);
                System.out.println("没有购买过诊断资格");
                return AjaxResult.me().setMessage("没有购买过诊断资格").setCode(201)
                        .setSuccess(false);
            }
            Date now = new Date();
            long nowTime = now.getTime();
            long time = date.getTime();
            if(time>nowTime){
                System.out.println("诊断有效期存在");
                return AjaxResult.me().setMessage("诊断有效期存在，且没过期，可以进行诊断")
                        .setSuccess(true);
            }else if (date == null || time == 0 || time <1){
                System.out.println("没有购买过诊断资格");
                return AjaxResult.me().setMessage("没有购买过诊断资格").setCode(201)
                        .setSuccess(false);
            }else {
                System.out.println("诊断有效期过期，需要重新购买");
                return AjaxResult.me().setMessage("诊断有效期过期，需要重新购买").setCode(201)
                        .setSuccess(false);
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("出现异常，请重试").setCode(201)
                    .setSuccess(false);
        }
    }

    /*
    * 检查心电报表次数
    * */
    @Override
    public AjaxResult checkReportNum(Long userID) {
        try {
            User userByID = userMapper.getUserByID(userID);
            Integer reportNum = userByID.getReportNum();
            if(reportNum !=null && reportNum>0){
                System.out.println("可以进行心电报表功能");
                return AjaxResult.me().setSuccess(true).setCode(200)
                        .setMessage("可以进行心电报表功能");
            }else if(reportNum == null || reportNum <0){
                System.out.println("没有购买过报表资格");
                return AjaxResult.me().setSuccess(false).setCode(201)
                        .setMessage("没有购买过报表资格");
            }else {
                System.out.println("报表次数为0,请购买");
                return AjaxResult.me().setSuccess(false).setCode(201)
                        .setMessage("报表次数为0,请购买");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("出现异常，请重试").setCode(201)
                    .setSuccess(false);
        }
    }


    @Override
    public AjaxResult findByPhone(String phone) {
        try {
            UserYVO user = userMapper.findByPhone(phone);
            return AjaxResult.me().setResultObj(user);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setCode(201).setMessage("查询失败");
        }
    }
}
